<!-- 排班管理 -->
<template>
  <div class="dashboard-container transport-task customer-list-box el-card_body">
    <!-- main  -->
    <div class="el-card">
      <!-- 表单 -->
      <el-form
        ref="formRef"
        :inline="true"
        class="demo-form-inline"
      >
        <el-row :gutter="60">
          <el-col :span="8">
            <el-form-item label="员工账号:">
              <el-input
                v-model="form.employeeNumber"
                placeholder="请输入员工账号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="员工姓名:">
              <el-input
                v-model="form.name"
                placeholder="请输入员工姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="工作模式"
              inline
            >
              <el-select
                v-model="form.workPatternId"
                placeholder="请选择工作模式"
                clearable
                style="width: 100%"
              >
                <!-- 渲染对象里面得数组 -->

                <el-option
                  v-for="item in workPatternList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 月份 -->
            <el-form-item
              label="月份:"
              class="month"
            >
              <el-date-picker
                v-model="form.month"
                value-format="yyyy-MM"
                type="month"
                placeholder="请选择月份"
                style="display: inline-block;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 下拉所属结构 -->
            <el-form-item
              label="所属机构:"
              label-width="80px"
            >
              <treeselect
                v-model="form.agencyId"
                :options="agencyOptions"
                :normalizer="normalizer"
                :searchable="true"
                style="width:405px"
                placeholder="请选择当前所在机构"
              />
              <img
                src="@/assets/pullDown.png"
                style="position:absolute;width:18px;height:18px;right:9px;top:12px;cursor:pointer;pointer-events:none;transition-duration:0.3s"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            style="padding-left:50px"
          >
            <el-button
              type="warning"
              @click="search"
            >搜索</el-button>
            <el-button
              plain
              class="reset-btn"
              @click="reset"
            >重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- body  -->
    <div class="el-card-table">
      <!-- 表体顶部按钮 -->
      <el-button
        type="warning"
        style="margin-bottom:20px"
        @click="$router.push('workArrange-setting')"
      >调度配置
      </el-button>
      <el-button
        plain
        style="margin-bottom:20px"
        @click="Bindingscheduling()"
      >绑定排班
      </el-button>
      <el-button
        plain
        class="daohang"
        @click="exportExcel"
      >导出Excel</el-button>
      <!-- table表格 -->
      <el-table
        v-loading="loading"
        :data="workList"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          fixed
          type="selection"
          width="55"
        >
        </el-table-column>
        <el-table-column
          fixed
          label="员工账号"
          prop="employeeNumber"
          width="100"
        >
        </el-table-column>
        <el-table-column
          fixed
          prop="name"
          label="员工姓名"
          width="120"
        >
        </el-table-column>
        <el-table-column
          fixed
          prop="phone"
          label="员工电话"
          width="120"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          fixed
          label="员工角色"
          width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span>{{ enumUserType(scope.row.userType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed
          prop="workPatternName"
          label="当前工作模式"
          width="110"
          show-overflow-tooltip
        >
        </el-table-column>
        <!-- 循环出来el-table-column 1-30 -->
        <el-table-column
          v-for="(item,index) in 30"
          :key="index+1"
          prop="workSchedules"
          width="80"
          :label="String(item)"
          show-overflow-tooltip
        >
          <!-- 拿到这一行数据 -->
          <template #default="{row}">
            <div
              v-if="row.workSchedules[index] === true"
              class="work"
            >上</div>
            <div
              v-else
              class="rest"
            >休</div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页居中显示 -->
      <el-pagination
        style="margin-top: 20px;"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <!-- 绑定排班  -->
    <el-dialog
      title="员工调整"
      :visible.sync="dialogFormVisible"
      width="25%"
    >
      <div class="FormCon">
        <el-form>
          <el-radio
            v-model="formDialg.workPatternType"
            label="1"
          >礼拜制</el-radio>
          <el-radio
            v-model="formDialg.workPatternType"
            label="2"
          >连续制</el-radio>
          <el-form-item
            label="模式名称"
            style="margin-top: 30px;"
          >
            <el-select
              v-model="formDialg.workPatternId"
              placeholder="请选择工作模式"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="item in formDialg.workPatternType === '1' ? weekList : continuousList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submit"
        >确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { utils, writeFileXLSX } from 'xlsx'
import { workManage, selectWorkHistoryList } from '@/api/transit.js'
import { agencyList } from '@/api/institutions'
import { peopleSet } from '@/api/transit'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Treeselect from '@riophae/vue-treeselect'
export default {
  components: {
    Treeselect
  },
  data () {
    return {
      // 加载
      loading: true,
      form: {
        // 网点
        agencyId: null,
        // 员工账号
        employeeNumber: '',
        // 月份
        month: '',
        // 员工名称
        name: '',
        // 页数
        page: '1',
        // 每页条数
        pageSize: '10',
        // 用户类型：1：员工，2：快递员，3:司机
        userType: '',
        // 工作模式ID 默认 0 ：无工作模式
        workPatternId: null
      },
      // 排班列表
      workList: [null],
      // 工作模式列表
      workPatternList: {},
      // 总条数
      total: 0,
      // 弹窗显示与隐藏
      dialogFormVisible: false,
      // 下拉列表
      agencyOptions: [],
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      formDialg: {
        userIdList: [],
        // 工作模式类型，1:礼拜制，2：连续制
        workPatternType: '1',
        // 工作模式id
        workPatternId: null
      },
      // 勾选
      selection: [],
      // 礼拜制列表
      weekList: [],
      // 连续制列表
      continuousList: [],
      // 绑定排班的工作模式下拉列表
      classList: []
    }
  },
  async created () {
    await this.getList()
  },
  mounted () {
    this.getWorkPattern()
    this.getAgency()
  },
  methods: {
    // 搜索
    search() {
      this.form.page = 1
      this.getList()
    },
    // 每页多少条
    handleSizeChange(val) {
      this.form.pageSize = val
      // 重新发送请求渲染列表
      this.getList()
    },
    // 当前第几页
    handleCurrentChange(val) {
      this.form.page = val
      // 重新发送请求渲染列表
      this.getList()
    },
    // 获取渲染列表
    async getList () {
      const {// 网点
        agencyId,
        // 员工账号
        employeeNumber,
        // 月份
        month,
        // 员工名称
        name,
        // 页数
        page,
        // 每页条数
        pageSize,
        // 用户类型：1：员工，2：快递员，3:司机
        userType,
        // 工作模式ID 默认 0 ：无工作模式
        workPatternId } = this.form
      const res = await workManage({
        agencyId,
        employeeNumber,
        // mm-yy格式
        month,
        name,
        page,
        pageSize,
        userType,
        workPatternId
      })
      this.loading = false
      console.log(res, '列表')
      this.workList = res.data.items
      this.total = +res.data.counts
    },
    // 渲染工作模式下拉
    async getWorkPattern () {
      const res = await selectWorkHistoryList()
      console.log(res, '工作模式')
      this.workPatternList = res.data[0]
      this.workPatternList = res.data[1]
      this.workPatternList = res.data[2]
      this.weekList = res.data[1]
      this.continuousList = res.data[2]
    },
    // 渲染所属机构下拉
    async getAgency () {
      const res = await agencyList()
      console.log(res, '所属机构')
      this.agencyOptions = JSON.parse(res.data)
    },
    // ! 清空表单
    reset() {
    // 清空表单
      this.form = {
        // 网点
        agencyId: null,
        // 员工账号
        employeeNumber: '',
        // 月份
        month: '',
        // 员工名称
        name: '',
        // 页数
        page: '1',
        // 每页条数
        pageSize: '10',
        // 用户类型：1：员工，2：快递员，3:司机
        userType: '',
        // 工作模式ID 默认 0 ：无工作模式
        workPatternId: null
      }
      this.getList()
    },
    handleSelectionChange(val) {
      this.selection = val
    },
    // 点击绑定排班
    Bindingscheduling() {
      if (this.selection.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择调整人员'
        })
        return
      }
      this.dialogFormVisible = true
      // 遍历拿到里面的id及userType用户类型给到formDialg对象里
      this.selection.forEach(item => {
        this.formDialg.userIdList.push(item.id)
        // console.log(item.userType, '用户类型')
        this.formDialg.userType = item.userType
      })
    },
    // 点击人工调整的确定
    async submit() {
      if (this.formDialg.workPatternId === null) {
        this.$message({
          type: 'error',
          message: '请选择模式名称'
        })
        return
      } else {
        await peopleSet(this.formDialg)
        this.$message({
          type: 'success',
          message: '操作成功！'
        })
        this.dialogFormVisible = false
        this.formDialg.workPatternId = null
        this.getList()
      }
    },
    // 枚举员工角色
    enumUserType (val) {
      // 1：员工，2：快递员，3:司机
      const obj = {
        '1': '员工',
        '2': '快递员',
        '3': '司机'
      }
      return obj[val]
    },
    // 点击导出
    async exportExcel() {
      const {// 网点
        agencyId,
        // 员工账号
        employeeNumber,
        // 月份
        month,
        // 员工名称
        name,
        // 页数
        page,
        // 每页条数
        pageSize,
        // 用户类型：1：员工，2：快递员，3:司机
        userType,
        // 工作模式ID 默认 0 ：无工作模式
        workPatternId } = this.form
      const res = await workManage({
        agencyId,
        employeeNumber,
        // mm-yy格式
        month,
        name,
        page,
        pageSize,
        userType,
        workPatternId
      })
      // 表头英文字段key（需要导出字段）
      const tableHeaderKeys = ['employeeNumber', 'name', 'phone', 'userType', 'workPatternName']
      // 表头中文字段value（设置表头使用）
      const tableHeaderValues = ['员工账号', '员工姓名', '员工电话', '员工角色', '当前工作模式']

      // 以excel表格的顺序调整后端数据（过滤）
      // workList数组里的userType用户类型：1：员工，2：快递员，3:司机
      const sheetData = res.data.items.map((item) => {
        const obj = {}
        // 1：员工，2：快递员，3:司机
        item.userType = this.enumUserType(item.userType)
        tableHeaderKeys.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })

      // 1.创建工作簿
      const workbook = utils.book_new()

      // 2.创建工作表
      // 需求一:导出所有字段数据
      const worksheet = utils.json_to_sheet(sheetData)

      // 需求二:导出部分字段数据
      // const worksheet = utils.json_to_sheet(data)

      // 给工作表设置表头得名字
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 给工作表设置列宽 工作表变量['!cols'] =[{ wch: 20 },第一列列宽 { wch: 10 }]第二列列宽
      // 第一种:给每一列设置
      // worksheet['!cols'] = [{ wch: 10 }, { wch: 20 }]
      // 第二种:给表头遍历统一设置相同列宽
      worksheet['!cols'] = tableHeaderValues.map(item => ({ wch: 20 }))

      // 3.把工作表插入到工作簿中
      utils.book_append_sheet(workbook, worksheet, '员工信息表')

      // 4.调用插件方法导出
      writeFileXLSX(workbook, `排班人员基本信息-${+new Date()}.xlsx`)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep th.date{
  .cell{
    padding-left: 17px!important;
  }
}
.work {
  width: 24px;
  height: 24px;
  background: #ffeeeb;
  border: 1px solid #e15536;
  border-radius: 50%;
  text-align: center;
  color: #e15536;
  font-size: 13px;
}
.el-form--inline {
  width: auto !important;
  ::v-deep .el-input__inner {
    width: 409px;
  }
}

.month {
  padding-left: 27px;
}

.workArrange-manage-people-setting {
  ::v-deep .el-dialog__body {
    padding: 30px 50px 10px 50px !important;
  }
  ::v-deep .el-dialog__footer {
    padding-bottom: 40px;
  }
}

.work-type {
  ::v-deep .el-form-item__content {
    margin-left: 40px !important;
  }
  ::v-deep .el-radio:first-child {
    margin-right: 80px !important;
  }
  ::v-deep.el-radio__label {
    font-weight: bold;
    color: #333333;
  }
}

.dialog-footer {
  text-align: center;
  .el-button {
    width: 89px;
    height: 36px;
    padding: 10px 20px;
  }
}

.rest {
  width: 24px;
  height: 24px;
  background: #eff3f8;
  border: 1px solid #d8dde3;
  border-radius: 50%;
  text-align: center;
  color: #20232a;
  font-size: 13px;
}

.alert {
  margin: 10px 0px;
}
.pagination {
  margin-top: 20px;
}
.transport-task ::v-deep .el-table td,
.el-table th {
  padding: 12px 0;
  min-width: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
  text-align: left;
  overflow: hidden;
}

// 下拉框
::v-deep .el-select {
  width: 100%;
}

/*定义滚动条轨道 内阴影+圆角*/
::v-deep .el-table--scrollable-x .el-table__body-wrapper {
  padding-bottom: 5px;
  margin-bottom: 5px;
  &::-webkit-scrollbar {
    height: 10px;
  }

  /*定义滑块 内阴影+圆角*/
  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: rgba(144, 147, 153, 0.3);
  }

  &::-webkit-scrollbar-track-piece {
    margin-right: 3px;
    margin-left: 3px;
  }
}

.dashboard-container {
  padding: 23px 20px 20px;
  margin-left: 30px;
}
::v-deep .el-card{
  overflow: initial;
  padding-top: 20px;
  padding-left: 0;
  width: 1670px;
  height: 160px;
  padding-left: 30px;
}
.customer-list-box {
  padding-top: 20px;
  padding-left: 0;
}
</style>

<style>

.el-form-item__label{
  font-weight: 400;
}

.el-button .el-button--default .is-plain {
  background: #ffeeeb;
  border-color: #f3917c;
  color: #e15536;
}

.el-card-table {
  margin-top: 20px;
  background-color: #FFF;
  height: 767px;
  width: 1670px;
  padding: 28px 28px 28px 28px;
}

.el-pagination {
  text-align: center;
  margin-bottom: 20px;
}

.el-card-table {
  height: 100%;
}

.FormCon {
  padding: 20px 40px
}

.el-radio__input.is-checked+.el-radio__label {
  font-weight: 700;
  color: #333;
}

.daohang {
  float: right;
  margin-right: 20px;
}

</style>
